<template>
	<div class="from">
		<h1>登录</h1>
		<el-form
			:model="ruleForm"
			status-icon
			:rules="rules"
			ref="ruleForm"
			label-width="100px"
			class="demo-ruleForm"
		>
			<el-form-item label="用户名" prop="username">
				<el-input v-model="ruleForm.username"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input
					type="password"
					v-model="ruleForm.password"
					autocomplete="off"
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm('ruleForm')"
					>提交</el-button
				>
				<el-button @click="resetForm('ruleForm')">重置</el-button>
				<el-button type="primary" @click="register()">注册</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	import { loginPost } from "@/http/request.js";
	export default {
		name: "LoginIndex",
		data() {
			var checkUser = (rule, value, callback) => {
				if (value.trim() == "") {
					callback(new Error("请输入用户名"));
				} else {
					callback();
				}
			};
			var validatePass = (rule, value, callback) => {
				if (value.trim() == "") {
					callback(new Error("请输入密码"));
				} else {
					callback();
				}
			};
			return {
				ruleForm: {
					password: "",
					username: "",
				},
				rules: {
					password: [{ validator: validatePass, trigger: "blur" }],
					username: [{ validator: checkUser, trigger: "blur" }],
				},
			};
		},
		methods: {
			register() {
				this.$router.push({ name: "register" });
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						loginPost("login", {
							username: this.ruleForm.username,
							password: this.ruleForm.password,
						})
							.then((res) => {
								let { data, meta } = res.data;
								if (meta.status == 200) {
									this.$message.success(meta.msg);
									localStorage.token = data.token;
									localStorage.username = data.username;
									setTimeout(() => {
										this.$router.push({ name: "index" });
									}, 1000);
								} else {
									this.$message.warning(meta.msg);
								}
							})
							.catch((err) => {
								console.log(err);
							});
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
		},
	};
</script>

<style soped>
	.from {
		width: 500px;
		margin: 30px auto;
	}
	h1 {
		text-align: center;
		margin-bottom: 10px;
	}
</style>